//
//  PlayerViewController.m
//  Boom
//
//  Created by 云鹏 赵 on 15/3/5.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "PlayerViewController.h"

@interface PlayerViewController ()

@end


@implementation PlayerViewController
@synthesize streamer = streamer;

+ (instancetype)sharePlayerDataHandel
{
    static PlayerViewController *player = nil;
    if (player == nil) {
        player = [[PlayerViewController alloc] init];
        player.view.backgroundColor  = [UIColor colorWithRed:239 / 255.0 green:238 / 255.0 blue:232 / 255.0 alpha:1];
    }
    return player;
}

- (void)dealloc
{
    [self destroyStreamer];
    if (progressUpdateTimer)
    {
        [progressUpdateTimer invalidate];
        progressUpdateTimer = nil;
    }
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // 添加背景图片
    
    // 隐藏navigation
    self.navigationController.navigationBarHidden = YES;
    
    

    
//    UIImage *backGroundImage = [UIImage imageNamed:@"player_albumblur_default@2x.png"];
//    UIImageView *backGroundImageView = [[UIImageView alloc] initWithImage:backGroundImage];
//    backGroundImageView.frame = [[UIScreen mainScreen] bounds];
//    [self.view addSubview:backGroundImageView];
//    [backGroundImageView release];
    
//
    // 创建提示lable(提示返回的方法)
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 90, 375, 20)];
    lable.backgroundColor = [UIColor clearColor];
    lable.text = @"向上滑动图片返回";
    lable.font = [UIFont systemFontOfSize:12.0];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.textColor = [UIColor colorWithRed:66 / 255.0 green:23 / 255.0 blue:0 alpha:1];
    [self.view addSubview:lable];
    [lable release];
    
    // 添加播放器imageView
    self.myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(62.5, 180, 250, 250)];
    self.myImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(buttonPressed)];
    [self.myImageView addGestureRecognizer:tap];
    [tap release];
    self.myImageView.backgroundColor = [UIColor clearColor];
    self.myImageView.layer.masksToBounds = YES;
    // 2. 设置图片圆角
    self.myImageView.layer.cornerRadius = 125;
    // 3. 设置边框宽度
    self.myImageView.layer.borderWidth = 0;
    // 4. 设置边框颜色
    self.myImageView.layer.borderColor = [UIColor whiteColor].CGColor;
    [self.view addSubview:self.myImageView];
    self.startCenter = self.myImageView.center;
    [_myImageView release];
    
    // 添加标签lable
    self.tagsLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 450, 335, 30)];
    self.tagsLable.backgroundColor = [UIColor clearColor];
    self.tagsLable.textColor = [UIColor lightGrayColor];
    self.tagsLable.textAlignment = NSTextAlignmentCenter;
    self.tagsLable.numberOfLines = 0;
    self.tagsLable.font = [UIFont systemFontOfSize:15.0];
    [self.view addSubview:self.tagsLable];
    [_tagsLable release];

    // 添加副标题lable
    self.titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 500, 335, 50)];
    self.titleLable.backgroundColor = [UIColor clearColor];
    //    self.titleLable.textColor = [UIColor colorWithRed:38 / 255.0 green:187 / 255.0 blue:102 / 255.0 alpha:1];
    self.titleLable.textColor = [UIColor colorWithRed:66 / 255.0 green:23 / 255.0 blue:0 alpha:1];
    self.titleLable.textAlignment = NSTextAlignmentCenter;
    self.titleLable.numberOfLines = 0;
    [self.view addSubview:self.titleLable];
    [_titleLable release];

    // 添加UISlider控件
//    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(self.myImageView.frame.origin.x,self.myImageView.frame.origin.y + self.myImageView.frame.size.height + 30, self.myImageView.frame.size.width, 10)];
//    [self.view addSubview:self.slider];
//    [_slider release];
//    self.slider.minimumValue = 0;
//    self.slider.maximumValue = 100;
//    self.slider.minimumTrackTintColor = [UIColor colorWithRed:38 / 255.0 green:187 / 255.0 blue:102 / 255.0 alpha:1];
//    self.slider.maximumTrackTintColor = [UIColor grayColor];
//    [self.slider addTarget:self action:@selector(sliderMoved:) forControlEvents:UIControlEventValueChanged];
//    [_slider release];
//    
//    // 播放button
//    self.button  = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.button.frame = CGRectMake(20, self.slider.frame.origin.y + 60, 80,80);
//    self.button .backgroundColor = [UIColor clearColor];
//    [self.button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.button];

    // 介绍scrol
//    self.richIntro = [[UIScrollView alloc] initWithFrame:CGRectMake(self.button.frame.origin.x + self.button.frame.size.width + 20, self.slider.frame.origin.y + 40, 235, 100)];
//    self.richIntro.backgroundColor = [UIColor clearColor];
//    self.richIntroLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 235, 100)];
//    self.richIntroLable.backgroundColor = [UIColor clearColor];
//    self.richIntroLable.font = [UIFont systemFontOfSize:13.0];
//    self.richIntroLable.textColor = [UIColor whiteColor];
//    self.richIntroLable.numberOfLines = 0;
//    [self.richIntro addSubview:self.richIntroLable];
//    [self.view addSubview:self.richIntro];
//    [_richIntro release];
//    [_richIntroLable release];
    
//    // 返回模态
//    UIImage *BarImage = [UIImage imageNamed:@"actionbutton@2x.png"];
//    BarImage = [BarImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:BarImage style:UIBarButtonItemStylePlain target:self action:@selector(barButtonAction:)];
    
    // MPVolumeView 控制系统音量
    MPVolumeView *volumeView = [[[MPVolumeView alloc] initWithFrame:self.volumeSlider.bounds] autorelease];
    [self.volumeSlider addSubview:volumeView];
    [volumeView sizeToFit];
    
    [self setButtonImageNamed:@"player_btn_play_normal@2x.png"];
    
}

// touch方法
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    self.startPoint = [touch locationInView:self.myImageView];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint newPoint = [touch locationInView:self.myImageView];
    CGFloat dy = newPoint.y - self.startPoint.y;
    if (dy > 0) {
        dy = 0;
    }
    self.myImageView.center = CGPointMake(self.myImageView.center.x, self.myImageView.center.y + dy);
    
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    self.endPoint = [touch locationInView:self.myImageView];
    if (self.endPoint.y <= 250) {
        self.myImageView.center = self.startCenter;
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    } else {
        self.myImageView.center = self.startCenter;
    }
}


//// 自定义scrollview高度方法
//+ (CGFloat)getHeightOfScrollView:(NSString *)richIntro
//{
//    CGSize size = CGSizeMake(235, 3000);
//    NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13.0] forKey:NSFontAttributeName];
//    CGRect frame = [richIntro boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
//    return frame.size.height;
//}

// 重写set方法
- (void)setRaido1ImageView:(Raido1ImageView *)raido1ImageView
{
    if (_raido1ImageView != raido1ImageView) {
        [_raido1ImageView release];
        _raido1ImageView = [raido1ImageView retain];
    }
    
    self.playUrl = _raido1ImageView.playUrl64;
//    self.title = _raido1ImageView.albumTitle;
    self.tagsLable.text = _raido1ImageView.albumTitle;
    self.titleLable.text = _raido1ImageView.title;
//    self.tagsLable.text = _raido1ImageView.tags;
    // 下载图片
    NSString *string = [_raido1ImageView.images objectAtIndex:0];
    NSURL *url = [NSURL URLWithString:string];
    [self.myImageView sd_setImageWithURL:url placeholderImage:nil];
    
    // scrollView 高度
//    float height = [[self class] getHeightOfScrollView:_raido1ImageView.richIntro];
//    self.richIntro.contentSize = CGSizeMake(235, height + 10);
//    self.richIntroLable.frame = CGRectMake(0, 0, 235, height + 10);
//    self.richIntroLable.text = _raido1ImageView.richIntro;
}

- (void)setPlayData:(PlayData *)playData
{
    if (_playData != playData) {
        [_playData release];
        _playData = [playData retain];
    }
    self.playUrl = _playData.playUrl64;
//    self.title = _playData.albumTitle;
    self.tagsLable.text = _playData.albumTitle;
    self.titleLable.text = _playData.title;
    // 下载图片
    NSString *string = _playData.coverLarge;
    NSURL *url = [NSURL URLWithString:string];
    [self.myImageView sd_setImageWithURL:url placeholderImage:nil];
    
    // scrollview 高度
//    float height = [[self class] getHeightOfScrollView:_playData.richIntro];
//    self.richIntro.contentSize = CGSizeMake(235, height + 10);
//    self.richIntroLable.frame = CGRectMake(0, 0, 235, height + 10);
//    self.richIntroLable.text = _playData.richIntro;
}
- (void)setRaido2:(Raido2 *)raido2
{
    if (_raido2 != raido2) {
        [_raido2 release];
        _raido2 = [raido2 retain];
    }
    // 下载图片
    NSString *string = _raido2.coverSmall;
    NSURL *url = [NSURL URLWithString:string];
    [self.myImageView sd_setImageWithURL:url placeholderImage:nil];
    
    self.playUrl = _raido2.playPath64;
//    self.title = _raido2.title;
    self.titleLable.text = _raido2.title;
    self.tagsLable.text = [NSString stringWithFormat:@"播放次数: %@", _raido2.playsCounts];
//    self.richIntroLable.text = @"请关注更过内容!";
    
}
- (void)setSearchTrack:(SearchTrack *)searchTrack
{
    if (_searchTrack != searchTrack) {
        [_searchTrack release];
        _searchTrack = [searchTrack retain];
    }
    self.playUrl = _searchTrack.play_path_64;
    self.titleLable.text = _searchTrack.title;
    self.tagsLable.text = _searchTrack.tags;
    NSLog(@"%@", self.titleLable);
    
    // 下载图片
    NSString *string = _searchTrack.cover_path;
    NSURL *url = [NSURL URLWithString:string];
    UIImage * image = [UIImage imageNamed:@"loadingbutton"];
    [self.myImageView sd_setImageWithURL:url placeholderImage:image];
    NSLog(@"%@",self.playUrl);
}

// 添加模态返回button方法
- (void)barButtonAction:(UIBarButtonItem *)bar
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

// 设置button图片
- (void)setButtonImageNamed:(NSString *)imageName
{
    if (!imageName)
    {
        imageName = @"player_btn_play_normal@2x";
    }
    [currentImageName autorelease];
    currentImageName = [imageName retain];
    
    UIImage *image = [UIImage imageNamed:imageName];
    
    [self.button.layer removeAllAnimations];
    [self.button setImage:image forState:0];
    
    if ([imageName isEqual:@"quan01_01@2x.png"])
    {
        [self spinButton];
    }
}

// 删除流，在UI更新计时器和变更通知
- (void)destroyStreamer
{
    if (streamer)
    {
        [[NSNotificationCenter defaultCenter]
         removeObserver:self
         name:ASStatusChangedNotification
         object:streamer];
        [progressUpdateTimer invalidate];
        progressUpdateTimer = nil;
        
        [streamer stop];
        [streamer release];
        streamer = nil;
    }
}

// 创建流
- (void)createStreamer
{
    
    if (streamer)
    {
        return;
    }
    
    [self destroyStreamer];
    
    NSString *escapedValue =
    [(NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                         nil,
                                                         (CFStringRef)self.playUrl,
                                                         NULL,
                                                         NULL,
                                                         kCFStringEncodingUTF8)
     autorelease];
    
    
    NSURL *url = [NSURL URLWithString:escapedValue];
    streamer = [[AudioStreamer alloc] initWithURL:url];
    
    progressUpdateTimer =
    [NSTimer
     scheduledTimerWithTimeInterval:0.1
     target:self
     selector:@selector(updateProgress:)
     userInfo:nil
     repeats:YES];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(playbackStateChanged:)
     name:ASStatusChangedNotification
     object:streamer];
}


//
// spinButton 数值调节按钮
//
// Shows the spin button when the audio is loading. This is largely irrelevant
// now that the audio is loaded from a local file.
// 显示了当音频加载旋转按钮。这在很大程度上是不相关的，现在的音响是从本地文件加载。
- (void)spinButton
{
    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanTrue forKey:kCATransactionDisableActions];
    CGRect frame = [self.button frame];
    self.button.layer.anchorPoint = CGPointMake(0.5, 0.5);
    self.button.layer.position = CGPointMake(frame.origin.x + 0.5 * frame.size.width, frame.origin.y + 0.5 * frame.size.height);
    [CATransaction commit];
    
    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanFalse forKey:kCATransactionDisableActions];
    [CATransaction setValue:[NSNumber numberWithFloat:2.0] forKey:kCATransactionAnimationDuration];
    
    CABasicAnimation *animation;
    animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = [NSNumber numberWithFloat:0.0];
    animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
    animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear];
    animation.delegate = self;
    [self.button.layer addAnimation:animation forKey:@"rotationAnimation"];
    
    [CATransaction commit];
}

//
// animationDidStop:finished:
//
// Restarts the spin animation on the button when it ends. Again, this is
// largely irrelevant now that the audio is loaded from a local file.
// 重新启动旋转动画上的按钮，它何时结束。同样，这在很大程度上是不相关的，现在的音响是从本地文件加载。
//
// Parameters:
//    theAnimation - the animation that rotated the button.
//    finished - is the animation finised?
//
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)finished
{
    if (finished)
    {
        [self spinButton];
    }
}

//
// buttonPressed:
//
// Handles the play/stop button. Creates, observes and starts the
// audio streamer when it is a play button. Stops the audio streamer when
// it isn't.
// 处理播放/停止按钮。创建，观察并启动时，它是一个播放按钮音频流光。停止音频流时，它不是。
// Parameters:
//    sender - normally, the play/stop button.
//

- (void)viewWillAppear:(BOOL)animated
{
    if ([self.streamer isPlaying] == YES) {
        // 旋转动画
        CABasicAnimation *basicAnimation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        basicAnimation2.fromValue = [NSNumber numberWithInt:0];
        basicAnimation2.toValue = [NSNumber numberWithInt:M_PI * 2];
        [basicAnimation2 setDuration:30];
        [basicAnimation2 setRepeatCount:NSIntegerMax];
        [self.myImageView.layer addAnimation:basicAnimation2 forKey:@"rotation"];

    }
}

- (void)buttonPressed
{
    if ([currentImageName isEqual:@"player_btn_play_normal@2x.png"])
    {
        [self createStreamer];
        [self setButtonImageNamed:@"quan01_01@2x.png"];
        [streamer start];
        
        // 旋转动画
        CABasicAnimation *basicAnimation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        basicAnimation2.fromValue = [NSNumber numberWithInt:0];
        basicAnimation2.toValue = [NSNumber numberWithInt:M_PI * 2];
        [basicAnimation2 setDuration:30];
        [basicAnimation2 setRepeatCount:NSIntegerMax];
        [self.myImageView.layer addAnimation:basicAnimation2 forKey:@"rotation"];
        
    }
    else
    {
        [self.myImageView.layer removeAnimationForKey:@"rotation"];
        [streamer pause];
        [self setButtonImageNamed:@"player_btn_play_normal@2x.png"];
    }
}
- (void)streamerStop
{
//    [self destroyStreamer];
    [streamer stop];

}

//
// sliderMoved:
//
// Invoked when the user moves the slider
//
// Parameters:
//    aSlider - the slider (assumed to be the progress slider)
//
//- (void)sliderMoved:(UISlider *)aSlider
//{
//    if (streamer.duration)
//    {
//        double newSeekTime = (aSlider.value / 100.0) * streamer.duration;
//        [streamer seekToTime:newSeekTime];
//    }
//}

//
// playbackStateChanged:
//
// Invoked when the AudioStreamer
// reports that its playback status has changed.
// 调用时的AudioStreamer，报告说，其播放状态发生了变化。
- (void)playbackStateChanged:(NSNotification *)aNotification
{
    if ([streamer isWaiting])
    {
        [self setButtonImageNamed:@"quan01_01@2x.png"];
    }
    else if ([streamer isPlaying])
    {
        [self setButtonImageNamed:@"player_btn_pause_normal@2x.png"];
    }
    else if ([streamer isIdle])
    {
        [self destroyStreamer];
        [self setButtonImageNamed:@"player_btn_play_normal@2x.png"];
    }
}

//
// updateProgress:
// 更新进度
// Invoked when the AudioStreamer
// reports that its playback progress has changed.
//


- (void)updateProgress:(NSTimer *)updatedTimer
{
    if (streamer.bitRate != 0.0)
    {
        
        double progress = streamer.progress;
        double duration = streamer.duration;
        
        if (duration > 0)
        {
            [self.slider setEnabled:YES];
            [self.slider setValue:(progress / duration) * 100 animated:YES];
        }
        else
        {
            [progressSlider setEnabled:NO];
            [self.slider setEnabled:NO];
        }
    }
    else
    {
        positionLabel.text = @"Time Played:";
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
